#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

class Solution
{
public:
    vector<long long> minOperations(vector<int> &nums, vector<int> &queries)
    {
        sort(nums.begin(), nums.end());
        vector<long long> prefix(nums.size());
        prefix[0] = nums[0];
        for (int i = 1; i < nums.size(); i++)
        {
            prefix[i] = prefix[i - 1] + nums[i];
        }
        vector<long long> ans(queries.size());
        for (int i = 0; i < queries.size(); i++)
        {
            long long q = queries[i];
            long long index = 0;
            if (nums.front() < q)
                index = lower_bound(nums.begin(), nums.end(), q) - nums.begin();
            if (index > 0)
            {
                long long addOPs = (index * q) - prefix[index - 1];
                long long subtractOPs = prefix[nums.size() - 1] - prefix[index - 1] - q * (nums.size() - index);
                ans[i] = addOPs + subtractOPs;
            }
            else
            {
                ans[i] = prefix[nums.size() - 1] - q * nums.size();
            }
        }
        return ans;
    }
};

int main()
{
    cout << "Code2602" << endl;
    Solution s;
    vector<int> nums = {3, 1, 6, 8};
    vector<int> queries = { 5};
    vector<long long> ans = s.minOperations(nums, queries);
    for (auto i : ans)
    {
        cout << i << " ";
    }
    return 0;
}